package com.contactbook.web.controller;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.contactbook.web.service.ContactClient;
import com.contactbook.web.service.GroupClient;

import contactbook.model.Account;

public class IndexController extends HttpServlet implements Servlet {
        
	private static final long serialVersionUID = 1L;
        
	private GroupClient groupClient;
	private ContactClient contactClient;
       
    public IndexController() {
        super();
        groupClient = new GroupClient();
        contactClient = new ContactClient();
    }
    
    public void init() throws ServletException {
        super.init();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		redirect(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	redirect(request, response);
    }
    
    private void redirect(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	HttpSession session = request.getSession(true);
    	Account account = (Account)session.getAttribute("account");
    	RequestDispatcher dispatcher = request.getRequestDispatcher("/index.jsp");
    	
    	if (account != null) {
			groupClient.login(account.getLogin(), account.getPassword());
            contactClient.login(account.getLogin(), account.getPassword());
	
			request.setAttribute("contactsWithoutGroup", contactClient.getContactsWithoutGroup());
			request.setAttribute("groups", groupClient.getGroups().toArray());
    		
    		contactClient.logout();
			groupClient.logout();
    	}
    	
    	dispatcher.forward(request, response);
    }
    
    public void destroy() {
            super.destroy();
    }

}
